// pages/localExperience/localExperience.js
import throttle from '../../utils/throttle.js';
import { hasPermission } from '../../utils/tools';
import { scrollToLeftEnd } from '../../utils/behavior';
const app = getApp();
Page({
    behaviors: [scrollToLeftEnd],
    /**
     * 页面的初始数据
     */
    data: {
        params: {},
        swiperHeight: '', //轮播窗口高度
        currentTabIndex: 0,
        tabsArr: [],
        // 更多操作
        show: false,
        actions: [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ],
        // 经验相关
        id: '',
        // 当前经验创建人id
        activeCreateUid: '',
        // 当前编辑类型，在添加经验页面时可能被修改
        activeTypeName: '全部',
        // 类型数组
        typenameArr: ['全部'],
        // 点击添加经验时对应的经验类型副本
        activeTypeNameCopy: '全部',
        showNext: false,
        permissionList: ['00', '01'],
    },

    handleLoad(e) {
        let { index } = e.currentTarget.dataset;

        let instance = this.selectComponent(`.experience${index}`);

        this.data.tabsArr[index].list = [];

        instance.data.responseArr.map((item) => {
            item.data.map((child) => {
                // 格式化时间
                child.createtime = app.timeago(child.createtime);
                child.ellipsis = child.content.length > 168;
                if (child.picurls) {
                    child.imageArrOfThree =
                        child.picurls.length > 3
                            ? child.picurls.slice(0, 3)
                            : child.picurls;
                } else {
                    child.imageArrOfThree = [];
                }
                this.data.tabsArr[index].list.push(child);
            });
        });

        this.setData({
            tabsArr: this.data.tabsArr,
        });
    },

    handleLoadingOver(e) {
        let { index } = e.currentTarget.dataset;
        this.setData({
            [`tabsArr[${index}].loadingAll`]: true,
        });
    },

    onTabsClick(e) {
        this.setData({
            currentTabIndex: e.detail.index,
            activeTypeName: e.detail.title,
        });
    },

    swiperChange(e) {
        if (e.detail.source === 'touch') {
            this.setData({
                currentTabIndex: e.detail.current,
                activeTypeName: this.data.typenameArr[e.detail.current],
            });
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 设置页面顶部title
        wx.setNavigationBarTitle({
            title: app.globalData.addressBack + '·当地经验',
        });
        let isSafeBottom = app.globalData.isIpx;
        var that = this;
        //  高度自适应
        wx.getSystemInfo({
            success: function (res) {
                let clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth,
                    swiperHeight;
                if (isSafeBottom) {
                    swiperHeight = clientHeight * rpxR - 242;
                } else {
                    swiperHeight = clientHeight * rpxR - 208;
                }

                that.setData({
                    swiperHeight: swiperHeight,
                });
            },
        });

        this.setData({
            params: {
                city: app.globalData.addressBack,
                country: app.globalData.countryBack,
            },
        });
        // 获取经验类别
        this.getExperienceTypeList();
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 预览图片
    previewImage(e) {
        let index = e.currentTarget.dataset.index;
        let images = JSON.parse(e.currentTarget.dataset.images) || [];

        wx.previewImage({
            current: images[index],
            urls: images,
        });
    },

    //获取经验类别列表
    getExperienceTypeList() {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/getExperienceTypeList?authId=${app.globalData.authId}`,
            method: 'GET',
            header: {
                'content-type': 'application/json',
            },
            success: function (res) {
                if (res.data.status === '0') {
                    res.data.data.map((item) => {
                        _that.data.typenameArr.push(item.typename);
                    });
                    _that.data.tabsArr = [
                        {
                            typename: '全部',
                            id: '',
                        },
                        ...res.data.data,
                    ];
                    _that.setData({
                        tabsArr: _that.data.tabsArr,
                        typenameArr: _that.data.typenameArr,
                    });
                }
            },
        });
    },

    refresh() {
        // 全部那个分类刷新
        let _that = this;
        _that.data.tabsArr[0].list = [];
        _that.setData(
            {
                tabsArr: _that.data.tabsArr,
            },
            () => {
                let instance0 = _that.selectComponent('.experience0');
                instance0 && instance0.refresh();
            }
        );

        // 刷新当前的经验类型列表
        let index = _that.data.typenameArr.indexOf(_that.data.activeTypeName);

        // 针对再次编辑修改类型前的经验类型列表
        let previousIndex = _that.data.typenameArr.indexOf(
            _that.data.activeTypeNameCopy
        );

        if (index > 0) {
            _that.data.tabsArr[index].list = [];
            _that.setData(
                {
                    tabsArr: _that.data.tabsArr,
                },
                () => {
                    let instance = _that.selectComponent(`.experience${index}`);
                    instance && instance.refresh();
                }
            );
        }

        if (index !== previousIndex && previousIndex > 0) {
            _that.data.tabsArr[previousIndex].list = [];
            _that.setData(
                {
                    tabsArr: _that.data.tabsArr,
                },
                () => {
                    let instancePrevious = _that.selectComponent(
                        `.experience${previousIndex}`
                    );
                    instancePrevious && instancePrevious.refresh();
                }
            );
        }
    },

    // 编辑
    edit(e) {
        let { id, uid, typename, excellentflg, authority } = e.detail;

        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (hasPermission(this.data.permissionList) || authority) {
            if (excellentflg === '00') {
                actions.splice(0, 0, {
                    name: '设置为精华',
                    color: '#333333',
                    id: 3,
                });
            } else {
                actions.splice(0, 0, {
                    name: '取消精华',
                    color: '#333333',
                    id: 4,
                });
            }

            actions.splice(2, 0, {
                name: '转移至',
                color: '#333333',
                id: 5,
            });
        }
        this.setData({
            show: true,
            id,
            activeCreateUid: uid,
            activeTypeName: typename,
            activeTypeNameCopy: typename,
            actions,
        });
    },

    // 取消编辑
    onCancel() {
        this.setData({
            show: false,
        });
    },

    // 选中后
    onSelect(e) {
        let _that = this;
        if (e.detail.id == 2) {
            _that.onCancel();
            wx.navigateTo({
                url: `../../releasePage/pages/addExperience/addExperience?type=02&id=${_that.data.id}&current=1`,
            });
        } else if (e.detail.id == 1) {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        wx.request({
                            url:
                                app.globalData.rootPath +
                                `cjMap/deleteExperience`,
                            method: 'GET',
                            header: {
                                'content-type':
                                    'application/x-www-form-urlencoded',
                            },
                            data: {
                                authId: app.globalData.authId,
                                id: _that.data.id,
                            },
                            success: function (res) {
                                if (res.data.status === '0') {
                                    app.globalData.expRefresh = true;
                                    app.globalData.indexExpRefresh = true;
                                    wx.showToast({
                                        title: '删除成功',
                                        icon: 'success',
                                        duration: 2000,
                                    });
                                    _that.onCancel();
                                    _that.refresh();
                                }
                            },
                        });
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.id == 3) {
            _that.setExperienceExcellent('01');
        } else if (e.detail.id == 4) {
            _that.setExperienceExcellent('00');
        } else if (e.detail.id == 5) {
            _that.setData({
                showNext: true,
            });
            _that.onCancel();
        }
    },

    // 设为精华和取消精华
    setExperienceExcellent(excellentflg) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/setExperienceExcellent?authId=${app.globalData.authId}`,
            header: {
                'content-type': 'application/json',
            },
            data: {
                excellentflg,
                id: _that.data.id,
            },
            success: function (res) {
                if (res.data.status == '0') {
                    app.globalData.expRefresh = true;

                    _that.onCancel();
                    _that.refresh();
                }
            },
        });
    },

    // 处理点赞同步问题
    handleLike(e) {
        let { id, praiseflg, praisecnt, typename } = e.detail;
        let expIndex = -1;
        let allExpIndex = -1;
        // 当前的经验类型列表
        let typeIndex = this.data.typenameArr.indexOf(typename);
        // 如果不是全部那个分类
        if (typeIndex > 0) {
            this.data.tabsArr[typeIndex].list.map((item, index) => {
                if (item.id === id) {
                    expIndex = index;
                }
            });
            if (expIndex > -1) {
                this.setData({
                    [`tabsArr[${typeIndex}].list[${expIndex}].praiseflg`]: praiseflg,
                    [`tabsArr[${typeIndex}].list[${expIndex}].praisecnt`]: praisecnt,
                });
            }
        }

        // 全部分类
        this.data.tabsArr[0].list.map((item, index) => {
            if (item.id === id) {
                allExpIndex = index;
            }
        });

        if (allExpIndex > -1) {
            this.setData({
                [`tabsArr[0].list[${allExpIndex}].praiseflg`]: praiseflg,
                [`tabsArr[0].list[${allExpIndex}].praisecnt`]: praisecnt,
            });
        }
    },

    // 点击评论图标直接跳转到底部评论区
    handleComment: throttle(
        (e) => {
            const { id } = e.detail;
            wx.navigateTo({
                url: `../../functionPage/pages/experienceDetail/experienceDetail?id=${id}&comment=1`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    // 刷新某一条经验的评论数
    refreshCommentNum(params) {
        const { id, commentcount, typename } = params;
        // 当前的经验类型列表
        let typeIndex = this.data.typenameArr.indexOf(typename);
        // 如果不是全部那个分类
        if (typeIndex > 0) {
            const expIndex = this.data.tabsArr[typeIndex].list.findIndex(
                (item) => {
                    return item.id === id;
                }
            );
            if (expIndex > -1) {
                this.setData({
                    [`tabsArr[${typeIndex}].list[${expIndex}].commentcount`]: commentcount,
                });
            }
        }

        // 全部分类
        const allExpIndex = this.data.tabsArr[0].list.findIndex((item) => {
            return item.id === id;
        });
        if (allExpIndex > -1) {
            this.setData({
                [`tabsArr[0].list[${allExpIndex}].commentcount`]: commentcount,
            });
        }
    },

    // 转移上一步
    upBtn(e) {
        this.setData({
            showNext: false,
            show: true,
        });
    },

    hideTranferCover(e) {
        this.setData({
            showNext: false,
        });
    },
});
